{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Visualizing Logistic Regression"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting data/train-images-idx3-ubyte.gz\n",
      "Extracting data/train-labels-idx1-ubyte.gz\n",
      "Extracting data/t10k-images-idx3-ubyte.gz\n",
      "Extracting data/t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import matplotlib.pyplot as plt\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "mnist      = input_data.read_data_sets('data/', one_hot=True)\n",
    "trainimg   = mnist.train.images\n",
    "trainlabel = mnist.train.labels\n",
    "testimg    = mnist.test.images\n",
    "testlabel  = mnist.test.labels"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Define the graph"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Parameters of Logistic Regression\n",
    "learning_rate   = 0.01\n",
    "training_epochs = 20\n",
    "batch_size      = 100\n",
    "display_step    = 5\n",
    "\n",
    "# Create Graph for Logistic Regression\n",
    "x = tf.placeholder(\"float\", [None, 784], name=\"INPUT_x\") \n",
    "y = tf.placeholder(\"float\", [None, 10], name=\"OUTPUT_y\")  \n",
    "W = tf.Variable(tf.zeros([784, 10]), name=\"WEIGHT_W\")\n",
    "b = tf.Variable(tf.zeros([10]), name=\"BIAS_b\")\n",
    "\n",
    "# Activation, Cost, and Optimizing functions\n",
    "pred = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax\n",
    "cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=1))\n",
    "optm = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) \n",
    "corr = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))    \n",
    "accr = tf.reduce_mean(tf.cast(corr, \"float\"))\n",
    "init = tf.initialize_all_variables()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Launch the graph"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "sess = tf.Session()\n",
    "sess.run(init)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Summary writer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Summary writer ready\n"
     ]
    }
   ],
   "source": [
    "summary_path = '/tmp/tf_logs/logistic_regression_mnist'\n",
    "summary_writer = tf.train.SummaryWriter(summary_path, graph=sess.graph)\n",
    "print (\"Summary writer ready\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Run"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch: 000/020 cost: 1.174416608 train_acc: 0.890\n",
      "Epoch: 005/020 cost: 0.446460936 train_acc: 0.890\n",
      "Epoch: 010/020 cost: 0.384964819 train_acc: 0.910\n",
      "Epoch: 015/020 cost: 0.362779245 train_acc: 0.860\n",
      "Optimization Finished!\n",
      "Test Accuracy: 0.912\n"
     ]
    }
   ],
   "source": [
    "for epoch in range(training_epochs):\n",
    "    sum_cost = 0.\n",
    "    num_batch = int(mnist.train.num_examples/batch_size)\n",
    "    # Loop over all batches\n",
    "    for i in range(num_batch): \n",
    "        randidx  = np.random.randint(trainimg.shape[0], size=batch_size)\n",
    "        batch_xs = trainimg[randidx, :]\n",
    "        batch_ys = trainlabel[randidx, :]                \n",
    "        # Fit training using batch data\n",
    "        feeds = {x: batch_xs, y: batch_ys}\n",
    "        sess.run(optm, feed_dict=feeds)\n",
    "        # Compute average loss\n",
    "        sum_cost += sess.run(cost, feed_dict=feeds)\n",
    "    avg_cost = sum_cost / num_batch\n",
    "    # Display logs per epoch step\n",
    "    if epoch % display_step == 0:\n",
    "        train_acc = sess.run(accr, feed_dict={x: batch_xs, y: batch_ys})\n",
    "        print (\"Epoch: %03d/%03d cost: %.9f train_acc: %.3f\" \n",
    "               % (epoch, training_epochs, avg_cost, train_acc))\n",
    "print (\"Optimization Finished!\")\n",
    "\n",
    "# Test model\n",
    "test_acc = sess.run(accr, feed_dict={x: testimg, y: testlabel})\n",
    "print ((\"Test Accuracy: %.3f\") % (test_acc))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Run the command line\n",
    "##### tensorboard --logdir=/tmp/tf_logs/logistic_regression_mnist\n",
    "### Open http://localhost:6006/ into your web browser"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\"images/tsboard/logistic_regression_mnist.png\">"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
